/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.ubc.cc.ajax;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apps.datastore.AccountInformationDatastore;
import com.apps.datastore.NotifierDatastore;
import com.apps.datastore.dao.AccountObject;
import com.apps.datastore.dao.ContactInformationObject;
import com.apps.datastore.dao.UniqueCourseObject;
import com.apps.datastore.dao.ContactInformationObject.CARRIER;
import com.google.appengine.api.datastore.EntityNotFoundException;

public class NotificationRequestController extends HttpServlet{
	
	NotifierDatastore d = new NotifierDatastore();
	AccountInformationDatastore ad = new AccountInformationDatastore();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
	String dept = req.getParameter("dept");
	String course = req.getParameter("course");
	String section = req.getParameter("section");
	Cookie[] cookies= req.getCookies();
	String user = null;
	for(int i = 0; i < cookies.length; i++) {
		if(cookies[i].getName().equals("user"))
			user = cookies[i].getValue();		
	}
	String xmlout = "<response>\n";
	if(user != null) {
		AccountObject ao = ad.getAccountObject(user);
		if(ao != null){
			long seatcfg = Long.parseLong(req.getParameter("seatcfg"));
			String email = ao.getEmail();
			String phoneNumber =ao.getPhoneNumber();
			long notifycfg = ao.getNotifyConfig();
			CARRIER carrier = ao.getCarrier();
			if((phoneNumber.isEmpty() || carrier.name().equals("NULL")) && notifycfg == 2)
				xmlout += "\t<message>Invalid carrier or phone number, check your account preferences</message>\n";
			else {
				boolean success;
				try {
					UniqueCourseObject uco = new UniqueCourseObject(dept,course,section);
					d.addCourse(uco);
					success = d.addNotifier(uco, new ContactInformationObject(email,phoneNumber,seatcfg,notifycfg,carrier));
					if(success)
						xmlout += "\t<message>Notification request was successfully added</message>\n";
					else
						xmlout += "\t<message>Notification request failed</message>\n";
				} catch (EntityNotFoundException e) {
					xmlout +="\t<message>Unexpected error has occured</message>\n";
				}

			}
		}
		else {
			xmlout += "\t<message>Account not found</message>\n";
		}
	}
	else {
		xmlout += "\t<message>Not logged in</message>\n";
	}
	xmlout += "</response>";
	try {
		resp.setContentType("text/xml; charset=UTF-8");
		resp.getWriter().write(xmlout);
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	}
}
